package com.manageserver.controller;

import com.managecommon.constant.MessageConstant;
import com.managecommon.result.Result;
import com.managecommon.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Author linye
 * @Date 2023-7-14 23:08
 * @Since 1.0.0
 * @Description 公共接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result upload(MultipartFile file){
        log.info("文件上传：{}", file);
        try {
            // 处理文件名唯一性
            String originalFilename = file.getOriginalFilename();   // 获取原始文件名
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".")); // 获取文件扩展名
            String newName = UUID.randomUUID().toString() + extension;

            // 返回文件的访问路径
            String filePath = aliOssUtil.upload(file.getBytes(), newName);
            return Result.success(filePath);
        } catch (IOException ex) {
            log.error("文件上传失败：{}", ex.getMessage());
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
